//
//  UIColor_HEX.swift
//  KTDouYu
//
//  Created by CoolKi on 16/5/4.
//  Copyright © 2016年 CoolKi. All rights reserved.
//

import UIKit

extension UIColor {
    
    class func kt_colorWithHexString(string : String,alpha : CGFloat)-> UIColor{
        let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
        var cString = string.stringByTrimmingCharactersInSet(characterSet)
        
        if cString.characters.count < 6 {
            return UIColor.clearColor()
        }
        if (cString.hasPrefix("0X") && cString.characters.count > 2){
            let index = cString.startIndex.advancedBy(2)
            cString = cString.substringFromIndex(index)
        }
        if cString.hasPrefix("#"){
            let index = cString.startIndex.advancedBy(1)
            cString = cString.substringFromIndex(index)
        }
        if cString.characters.count != 6 {
            return UIColor.clearColor()
        }
        let range_R = Range(start: cString.startIndex.advancedBy(0), end: cString.startIndex.advancedBy(2))
        let range_G = Range(start: cString.startIndex.advancedBy(2), end: cString.startIndex.advancedBy(4))
        let range_B = Range(start: cString.startIndex.advancedBy(4), end: cString.startIndex.advancedBy(6))
        let string_r = cString.substringWithRange(range_R)
        let string_g = cString.substringWithRange(range_G)
        let string_b = cString.substringWithRange(range_B)
        //print(string_r,string_g,string_b)
        
        var r = uint()
        var g = uint()
        var b = uint()
        
        NSScanner(string: string_r).scanHexInt(&r)
        NSScanner(string: string_g).scanHexInt(&g)
        NSScanner(string: string_b).scanHexInt(&b)
        
        let float_r : CGFloat = CGFloat(r)/CGFloat(255.0)
        let float_g : CGFloat = CGFloat(g)/CGFloat(255.0)
        let float_b : CGFloat = CGFloat(b)/CGFloat(255.0)
        
        return UIColor(red: float_r, green: float_g, blue: float_b, alpha: alpha)
        
    }
    
}







